package com.example.jsonformateapplication.handler;

import ch.qos.logback.core.model.processor.ModelHandlerException;
import com.example.jsonformateapplication.entity.ApiResponseDate;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author 胡新毅 乐武护
 * @since 2024/9/14
 * 全局异常处理器，用于捕获全局异常，并返回json格式的错误信息
 */
@RestControllerAdvice //声明一个控制器增强器，用于捕获异常
public class GlobalExceptionHandler {
    @ExceptionHandler(ModelHandlerException.class)
    public ApiResponseDate<?> handlerException(MethodArgumentNotValidException ex){
        return ApiResponseDate.error("参数消炎失败"+ex.getBindingResult().getAllErrors().get(0).getDefaultMessage());
    }
    @ExceptionHandler(Exception.class)
    public ApiResponseDate<?> handlerGlobalException(Exception ex){
        return ApiResponseDate.error("系统异常"+ex.getMessage());
    }
}
